/* Copyright (c) 2011-2013 ISP RAS, Moscow. For more information please write to
 
      mermakov@ispras.ru
      svartanov@ispras.ru

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package ru.ispras.coffeemachine.instrument;

import java.util.ArrayList;
import java.util.List;

import org.apache.bcel.generic.ALOAD;
import org.apache.bcel.generic.ClassGen;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.DUP;
import org.apache.bcel.generic.DUP2;
import org.apache.bcel.generic.I2L;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.LDC_W;
import org.apache.bcel.generic.POP;
import org.apache.bcel.generic.PUSH;

import ru.ispras.coffeemachine.instrument.util.Utility;
import ru.ispras.coffeemachine.target.Type;

/**
 * TSan trace instrumentation
 * 
 * @author Sergey Vartanov (me@enzet.ru)
 * @version 1.2.0
 * @since 2012-12-20
 */

public class ConcurrencyMilk extends Milk
{
	public ConcurrencyMilk(ClassGen targetClass, ConstantPoolGen cpg)
	{
		super(targetClass, cpg);
		className = "Concurrency";
	}

	private static List<CustomListGenerator> customListGenerators;

	static {
		customListGenerators = new ArrayList<CustomListGenerator>();
		/* android.os.Handler:handleMessage */
		customListGenerators.add(new CustomListGenerator() {
			@Override
			public boolean checkApplicability(Milk milk) {

				return (Utility.extendsSuperClass(milk.targetClass.getJavaClass(), "android.os.Handler") ||
				        Utility.implementsInterface(milk.targetClass.getJavaClass(), "android.os.Handler$Callback")) &&
						milk.currentMethod.getName().equals("handleMessage");
			}

			@Override
			public InstructionList generateEnterList(Milk milk) {

				InstructionList result = new InstructionList();
				result.append(new ALOAD(1));
				milk.updateCodePosition(result);
				milk.appendMethod("enter_android_os_Handler_handleMessage", "(Ljava/lang/Object;I)V", result);

				return result;
			}

			@Override
			public InstructionList generateExitList(Milk milk) {

				return null;
			}
		});

		/* android.app.Application:OnCreate */
		customListGenerators.add(new CustomListGenerator() {
			@Override
			public boolean checkApplicability(Milk milk) {

				return Utility.extendsSuperClass(milk.targetClass.getJavaClass(), "android.app.Application") &&
						milk.currentMethod.getName().equals("onCreate");
			}

			@Override
			public InstructionList generateEnterList(Milk milk) {

				InstructionList result = new InstructionList();
				result.append(new ALOAD(0));
				milk.updateCodePosition(result);
				milk.appendMethod("enter_android_app_Application_onCreate", "(Ljava/lang/Object;I)V", result);

				return result;
			}

			@Override
			public InstructionList generateExitList(Milk milk) {

				InstructionList result = new InstructionList();
				result.append(new ALOAD(0));
				milk.updateCodePosition(result);
				milk.appendMethod("exit_android_app_Application_onCreate", "(Ljava/lang/Object;I)V", result);

				return result;
			}
		});

		/* java.lang.Thread */
		/*customListGenerators.add(new CustomListGenerator() {

			@Override
			public InstructionList generateExitList(Milk milk) {

				InstructionList result = new InstructionList();
				milk.updateCodePosition(result);
				milk.createMethod("exit_java_lang_Thread_run", "(I)V", result);

				return result;
			}

			@Override
			public InstructionList generateEnterList(Milk milk) {

				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public boolean checkApplicability(Milk milk) {

				return (Utility.implementsInterface(milk.currentClass.getJavaClass(), "java.lang.Runnable") ||
						Utility.extendsSuperClass(milk.currentClass.getJavaClass(), "java.lang.Thread")) &&
								milk.currentMethod.getName().equals("run");
			}
		});*/
	}

	/*
	 * Creation actions
	 */

	@Override
	protected InstructionList createFirstList()
	{
		if (!isInit()) {
		InstructionList result = new InstructionList();

			for (CustomListGenerator customListGenerator : customListGenerators) {
				if (customListGenerator.checkApplicability(this)) {
					InstructionList customList = customListGenerator.generateEnterList(this);
					if (customList != null) {
						result.append(customList);
					}
				}
			}
			if (currentMethod.isSynchronized()) {
				updateCodePosition(result);
				if (currentMethod.isStatic()) {
					result.append(new LDC_W(cpg.lookupClass(currentMethod.getClassName())));
				} else {
					result.append(new ALOAD(0));
				}
				appendMethod("methodEnterSync", "(ILjava/lang/Object;)V", result);
			} else {
				updateCodePosition(result);
				appendMethod("methodEnter", "(I)V", result);
			}
			return result;
		}
		return null;
	}

	/*
	 * Instructions
	 */

	@Override
	protected void xaload(Type type)
	{
/*		if ((type != Type.B) && (type != Type.Z))
		{
			updateCodePosition();
			createMethod("xaload" + type.getSignature() + "Direct",
			                        "([" + type.getJavaSignature() + "II)" + type.getJavaSignature());
			removeInstruction = true;
		}
		else
		{*/
			instructionList.append(new DUP2());
			updateCodePosition();
			appendMethod("xaload", "(Ljava/lang/Object;II)V");
		//}
	}

	@Override
	protected void xastore(Type type)
	{
		if ((type != Type.B) && (type != Type.Z))
		{
			updateCodePosition();
			appendMethod("xastore" + type.getSignature() + "Direct",
			                        "([" + type.getJavaSignature() + "I" + type.getJavaSignature() + "I)V");
			removeInstruction = true;
		}
		else
		{
			Type[] types = {Type.A, Type.I, type};
			int[] indexes = {0, 1};

			instructionList.append(factory.getElements(types, indexes, currentMethod.getMaxLocals()));

			updateCodePosition();
			appendMethod("xastore", "(Ljava/lang/Object;II)V");
		}
	}

	@Override
	protected void xreturn(boolean popStack)
	{
		if (!isInit())
		{
			if (currentMethod.isSynchronized()) {
				if (currentMethod.isStatic()) {
					instructionList.append(new LDC_W(cpg.lookupClass(currentMethod.getClassName())));
				} else {
					instructionList.append(new ALOAD(0));
				}
				updateCodePosition();
				appendMethod("monitorExit", "(Ljava/lang/Object;I)V");
			}

			updateCodePosition();
			appendMethod("methodExit", "(I)V");
			for (CustomListGenerator customListGenerator : customListGenerators) {
				if (customListGenerator.checkApplicability(this)) {
					InstructionList customList = customListGenerator.generateExitList(this);
					if (customList != null) {
						instructionList.append(customList);
					}
				}
			}
		}
	}

	@Override
	protected void getstatic(Object[] arguments)
	{
		if (!isInitOrClinit())
		{
			int identity = ((String) arguments[0]).hashCode();

			if (!((String)arguments[0]).contains("$VRc")) {
				instructionList.append(new PUSH(cpg, identity));
				instructionList.append(new I2L());
				instructionList.append(new PUSH(cpg, Utility.isVolatileVariable(targetClass.getJavaClass(),
				                                                                (String)arguments[0])));
				updateCodePosition();
				appendMethod("getstatic", "(JZI)V");
			}

		}
	}

	@Override
	protected void putstatic(Object[] arguments) {

		if (!isInitOrClinit())
		{
			long identity = ((String) arguments[0]).hashCode();
			if (!((String)arguments[0]).contains("$VRc")) {
				instructionList.append(new PUSH(cpg, identity));
				instructionList.append(new PUSH(cpg, Utility.isVolatileVariable(targetClass.getJavaClass(),
				                                                                (String)arguments[0])));
				updateCodePosition();
				appendMethod("putstatic", "(JZI)V");
			}
		}

	}

	@Override
	protected void getfield(Object[] arguments)
	{
		if (!isInitOrClinit())
		{
			instructionList.append(new DUP());
			instructionList.append(new PUSH(cpg, (String) arguments[0]));
			updateCodePosition();
			if (Utility.isVolatileVariable(targetClass.getJavaClass(), (String)arguments[0]))
			{
				appendMethod("getvolatile", "(Ljava/lang/Object;Ljava/lang/String;I)V");
			}
			else
			{
				appendMethod("getfield", "(Ljava/lang/Object;Ljava/lang/String;I)V");
			}
		}
	}

	@Override
	protected void putfield(Object[] arguments)
	{
		if (!isInitOrClinit())
		{
			Type type = Type.fromString((String) arguments[1]);

			if (type != null)
			{
				if (type.getItemSize() == 1)
				{
					instructionList.append(new DUP2());
					instructionList.append(new POP());
				}
				else
				{
					Type[] types = {Type.R, type};
					int[] indexes = {0};
					instructionList.append(factory.getElements(types, indexes, currentMethod.getMaxLocals()));
				}
				instructionList.append(new PUSH(cpg, (String) arguments[0]));
				updateCodePosition();
				if (Utility.isVolatileVariable(targetClass.getJavaClass(), (String)arguments[0]))
				{
					appendMethod("putvolatile", "(Ljava/lang/Object;Ljava/lang/String;I)V");
				}
				else
				{
					appendMethod("putfield", "(Ljava/lang/Object;Ljava/lang/String;I)V");
				}
			}
		}
	}

	/**
	 * Method invocation. There are 3 classes of methods: open methods (bytecode
	 * occurs in trace), close methods without taint results (simulate), close
	 * methods with taint result (interpret).
	 * <p>
	 * Thread identifier detection for <tt>run()</tt> or <tt>start()</tt>
	 * methods.
	 *
	 * @param type method type (0 for virtual, 1 for special, 2 for static and 3
	 *        for interface)
	 */
	@Override
	protected void invoke(Object []parameters, short type)
	{
		String className = (String)parameters[0];
		String method = (String)parameters[1];
		String signature = (String)parameters[2];
		className = getRealClassName(className, method, signature);

		boolean noLock = true;
		if ((method.equals("run") || method.equals("start")) && signature.equals("()V"))
		{
			updateCodePosition();
			appendMethod("lock", "(I)V");
			noLock = false;
			instructionList.append(new DUP());
			appendMethod("pr", "(Ljava/lang/Object;)V");
		}

		InstructionList inv = Invoker.createBeforeList(className, method, signature);

		if (inv.size() != 0) {
			if (noLock) {
				updateCodePosition();
				appendMethod("lock", "(I)V");
				appendMethod("sblock", "()V"); // before method call
				instructionList.append(inv);
				appendMethod("unlock", "()V");
			} else {
				appendMethod("sblock", "()V"); // before method call
				instructionList.append(inv);
				appendMethod("unlock", "()V");
			}
		} else {
			if (noLock) {
				//if (!className.startsWith("java/")) {
					updateCodePosition();
					appendMethod("sblock", "(I)V"); // before method call
				//}
			} else {
				appendMethod("sblock", "()V"); // before method call
				appendMethod("unlock", "()V");
			}
		}
	}

	@Override
	protected void athrow()
	{
		if (!isInit())
		{
			if (isLastInstruction)
			{
				if (currentMethod.isSynchronized()) {
					if (currentMethod.isStatic()) {
						instructionList.append(new LDC_W(cpg.lookupClass(currentMethod.getClassName())));
					} else {
						instructionList.append(new ALOAD(0));
					}
					updateCodePosition();
					appendMethod("monitorExit", "(Ljava/lang/Object;I)V");
				}
				updateCodePosition();
				appendMethod("methodExit", "(I)V");
				for (CustomListGenerator customListGenerator : customListGenerators) {
					if (customListGenerator.checkApplicability(this)) {
						InstructionList customList = customListGenerator.generateExitList(this);
						if (customList != null) {
							instructionList.append(customList);
						}
					}
				}
			}
			else
			{
				updateCodePosition();
				appendMethod("athrow", "(I)V");
			}
		}
	}

	@Override
	protected void monitor(boolean isEnter)
	{
		instructionList.append(new DUP());

		if (!isEnter)
		{
			updateCodePosition();
			appendMethod("monitorExit", "(Ljava/lang/Object;I)V");
		}
	}

	/*
	 * After instructions
	 */

	@Override
	protected void invokeAfter(Object []parameters, short type)
	{
		String className = (String)parameters[0];
		String method = (String)parameters[1];
		String signature = (String)parameters[2];
		className = getRealClassName(className, method, signature);

		InstructionList inv = Invoker.createAfterList(className, method, signature);

		boolean blockExitAdded = false;

		if (inv != null)
		{
			if (inv.size() != 0)
			{
				updateCodePosition();
				appendMethod("lock", "(I)V");
				instructionList.append(inv);
				appendMethod("sblock", "()V");
				blockExitAdded = true;
				appendMethod("unlock", "()V");
			}
		}

		if (!blockExitAdded)// && !className.startsWith("java/") && !Invoker.isBefore(className, method, signature))
		{
			updateCodePosition();
			appendMethod("sblock", "(I)V");
		}

	}

	@Override
	protected void monitorAfter(boolean isEnter)
	{
		if (isEnter)
		{
			updateCodePosition();
			appendMethod(isEnter ? "monitorEnter" : "monitorExit", "(Ljava/lang/Object;I)V");
		}
	}

}
